// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
const MAX_LIMIT = 20

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  const countResult = await db.collection('bill_tables').count()
  const total = countResult.total
  //最多取100个
  const batchTimes = Math.ceil(total / 100)
  const bills = []
  //
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection('bill_tables').orderBy('tableNo', 'asc').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    bills.push(promise)
  }
  // 等待所有
  return (await Promise.all(bills)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
}